package stack.hard;

import java.util.Stack;

/**
 * 最长有效括号
 */
public class LongestValidParentheses_32 {

    public int longestValidParentheses(String s) {
        if (s.length() == 0) {
            return 0;
        }
        Stack<Integer> stack = new Stack<>();
        int max = 0;
        for (int i = 0, le = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(i);
            } else {
                if (!stack.isEmpty()) {
                    stack.pop();
                    //"()(()"
                    if (stack.isEmpty()){
                        max = Math.max(max, i - le + 1);
                    } else {
                        max = Math.max(max, i - stack.peek());
                    }
                } else {
                    le = i + 1;
                }
            }
        }
        return max;
    }

    public static void main(String[] args) {
        LongestValidParentheses_32 lv = new LongestValidParentheses_32();
        //"()(()"
        System.out.println(lv.longestValidParentheses("()(()"));
    }
}
